package org.third.integration.auth.jaas.hello;

import java.io.IOException;

import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.servlet.http.HttpServletRequest;

public class HelloCallbackHandler implements CallbackHandler {
    HttpServletRequest request;

    public HelloCallbackHandler(HttpServletRequest request) {
        this.request = request;
    }

    @Override
    public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
        for (int index = 0; index < callbacks.length; index++) {
            if (callbacks[index] instanceof NameCallback) {
                NameCallback ncb = (NameCallback) callbacks[index];
                System.out.println("NameCallback prompt:" + ncb.getPrompt());

                ncb.setName(request.getParameter("username"));
            }
            if (callbacks[index] instanceof PasswordCallback) {
                PasswordCallback pcb = (PasswordCallback) callbacks[index];
                System.out.println("PasswordCallback prompt:" + pcb.getPrompt());
                pcb.setPassword(request.getParameter("password").toCharArray());
            }
        }
    }
}